from pydantic import BaseModel, Field
from typing import Optional, List
from datetime import datetime
from .response import SuccessResponse, PaginatedResponse


class UploadImageRequest(BaseModel):
    """上传图片请求（通过文件上传，此处仅作文档说明）"""
    pass


class UploadImageResponse(BaseModel):
    """上传图片响应"""
    image_url: str = Field(..., description="阿里云OSS完整URL地址", alias="imageUrl")
    oss_path: str = Field(..., description="OSS存储路径", alias="ossPath")
    
    class Config:
        populate_by_name = True


class ImageInfo(BaseModel):
    """图片信息"""
    image_url: str = Field(..., description="OSS图片URL地址", alias="imageUrl")
    angle: str = Field(..., description="拍摄角度：top(头顶面)、side(头侧面)、back(头后面)")
    oss_path: Optional[str] = Field(None, description="OSS存储路径（系统自动从URL提取，前端无需传递）", alias="ossPath")
    
    class Config:
        populate_by_name = True





class SaveImageRequest(BaseModel):
    """保存图片信息到数据库请求"""
    image_url: str = Field(..., description="OSS图片URL地址", alias="imageUrl")
    oss_path: str = Field(..., description="OSS存储路径", alias="ossPath")
    
    class Config:
        populate_by_name = True


class SaveImageResponse(BaseModel):
    """保存图片信息到数据库响应"""
    record_id: int = Field(..., description="记录ID", alias="recordId")
    image_url: str = Field(..., description="图片URL", alias="imageUrl")
    oss_path: str = Field(..., description="OSS路径", alias="ossPath")
    created_at: datetime = Field(..., description="创建时间", alias="createdAt")
    
    class Config:
        populate_by_name = True


class DetectionResult(BaseModel):
    """检测结果"""
    basp_type: str = Field(..., description="BASP分型结果", alias="baspType")
    severity: str = Field(..., description="脱发严重程度")
    description: str = Field(..., description="检测结果描述")
    suggestion: str = Field(..., description="护理建议")
    confidence: float = Field(..., description="检测置信度(0-1)")
    is_valid: bool = Field(..., description="检测结果是否有效", alias="isValid")
    
    class Config:
        populate_by_name = True





class DetectionHistoryItem(BaseModel):
    """检测历史项"""
    id: int = Field(..., description="记录ID")
    image_url: str = Field(..., description="主图片URL（向后兼容）", alias="imageUrl")
    images_info: List[ImageInfo] = Field(..., description="三个部位的照片信息", alias="imagesInfo")
    result: Optional[DetectionResult] = Field(None, description="检测结果")

    created_at: datetime = Field(..., description="检测时间", alias="createdAt")
    
    class Config:
        populate_by_name = True
        from_attributes = True


class DetectionHistoryRequest(BaseModel):
    """检测历史请求"""
    page: int = Field(1, ge=1, description="页码")
    limit: int = Field(10, ge=1, le=100, description="每页数量")


class DetectionHistoryResponse(BaseModel):
    """检测历史响应"""
    list: List[DetectionHistoryItem] = Field(..., description="检测记录列表")
    total: int = Field(..., description="总数量")
    has_more: bool = Field(..., description="是否有更多", alias="hasMore")
    
    class Config:
        populate_by_name = True


# 分步检测相关Schema
class StepDetectionRequest(BaseModel):
    """单步检测请求"""
    session_id: Optional[str] = Field(None, description="检测会话ID（首次检测时为空，后续步骤需要传递）", alias="sessionId")
    image_info: ImageInfo = Field(..., description="单张图片信息", alias="imageInfo")
    
    class Config:
        populate_by_name = True


class SingleImageResult(BaseModel):
    """单张图片检测结果"""
    angle: str = Field(..., description="检测角度")
    analysis: str = Field(..., description="单张图片分析结果")
    image_url: str = Field(..., description="图片URL", alias="imageUrl")
    processed_at: datetime = Field(..., description="处理时间", alias="processedAt")
    
    class Config:
        populate_by_name = True


class StepDetectionResponse(BaseModel):
    """单步检测响应"""
    session_id: str = Field(..., description="检测会话ID", alias="sessionId")
    step: int = Field(..., description="当前步骤（1-4）")
    total_steps: int = Field(..., description="总步骤数", alias="totalSteps")
    current_result: SingleImageResult = Field(..., description="当前步骤检测结果", alias="currentResult")
    is_completed: bool = Field(..., description="是否完成所有步骤", alias="isCompleted")
    next_angle: Optional[str] = Field(None, description="下一步需要的角度（如果未完成）", alias="nextAngle")
    
    class Config:
        populate_by_name = True


class FinalSummaryRequest(BaseModel):
    """最终汇总请求"""
    session_id: str = Field(..., description="检测会话ID", alias="sessionId")
    
    class Config:
        populate_by_name = True


class FinalSummaryResponse(BaseModel):
    """最终汇总响应"""
    session_id: str = Field(..., description="检测会话ID", alias="sessionId")
    record_id: int = Field(..., description="检测记录ID", alias="recordId")
    result: DetectionResult = Field(..., description="最终检测结果")
    images_info: List[ImageInfo] = Field(..., description="所有参与检测的图片信息", alias="imagesInfo")
    step_results: List[SingleImageResult] = Field(..., description="各步骤检测结果", alias="stepResults")
    
    class Config:
        populate_by_name = True


class ImagePreprocessingRequest(BaseModel):
    """图片预处理请求"""
    image_urls: List[str] = Field(..., description="三张图片的URL数组", alias="imageUrls")
    
    class Config:
        populate_by_name = True


class ImagePreprocessingResponse(BaseModel):
    """图片预处理响应"""
    is_all_valid: bool = Field(..., description="所有图片是否都可用", alias="isAllValid")
    
    class Config:
        populate_by_name = True


# 类型别名定义
DetectionUploadResponse = SuccessResponse[UploadImageResponse]
DetectionSaveResponse = SuccessResponse[SaveImageResponse]

DetectionHistoryListResponse = SuccessResponse[DetectionHistoryResponse]
StepDetectionApiResponse = SuccessResponse[StepDetectionResponse]
FinalSummaryApiResponse = SuccessResponse[FinalSummaryResponse]
ImagePreprocessingApiResponse = SuccessResponse[ImagePreprocessingResponse]